<template>
  <Drawer>
    <!-- 表单 -->
    <BaseForm />
  </Drawer>
</template>

<script lang="ts" setup>
import type {
  BindDetail,
  BindDetailResp,
  BindListReq,
} from '#/api/agent/model/bindModel';

import { computed } from 'vue';

import { useVbenDrawer, type VbenFormSchema } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import { getAgentBindById, updateAgentBind } from '#/api/agent/bind';

// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
const bindAgentList = ref<{ label: string; value: number }[]>([]);
// 表单实例
const bindFormRef = ref();

// 创建动态的schema
const formSchema = computed(() => [
  {
    component: 'Input',
    fieldName: 'username',
    label: $t('customer.list.bind'),
    disabled: true,
    componentProps: {
      placeholder: ' ',
    },
  },
  {
    component: 'CheckboxGroup',
    componentProps: {
      options: bindAgentList.value,
    },
    fieldName: 'agentId',
    label: $t('customer.bind.bindagent'),
  },
]);

// 定义表单
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false, // 不显示操作按钮
  layout: 'vertical',
  schema: formSchema as unknown as VbenFormSchema[],
});

// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  onConfirm: async () => {
    const { type, id } = drawerApi.getData<Record<string, any>>();
    const isPass = (await baseFormApi.validateAndSubmitForm()) as BindListReq; // 校验表单
    if (!isPass) {
      return; // 校验不通过
    } // 验证表单
    if (type === 'editData') {
      addOrEditDictionaryHandle(isPass, id);
    }
  },

  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 设置默认值
      const { type, id } = drawerApi.getData<Record<string, any>>();
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        getMenuDetailInfo(id);
      }
    } else {
      // 关闭弹窗时重置表单
      bindFormRef.value?.formRef?.resetFields();
    }
  },
});

/**
 * @author Buke
 * @description 新增或者编辑
 * @param {Record<string, any>} formData - 表单数据对象。
 * @param {number} id - ID（可选）。
 * @returns {void}
 */
async function addOrEditDictionaryHandle(
  formData: BindListReq,
  id?: number,
): Promise<void> {
  const data = {
    ...formData,
    userId: id,
  };

  await updateAgentBind(data);
  ElMessage.success($t('common.operateSuccess'));
  emit('refresh');
}

/**
 * @author Buke
 * @description 详情数据回显
 * @param {number} id - 要回显的绑定的客服ID。
 * @returns {void}
 */
async function getMenuDetailInfo(id: number): Promise<void> {
  drawerApi.setState({ loading: true });
  await getAgentBindById(id).then((res: BindDetailResp) => {
    baseFormApi.setValues({
      ...res,
      agentId: res.list
        .filter((item: any) => item.isBind)
        .map((item: any) => item.id),
    });
    bindAgentList.value = res.list.map((item: BindDetail) => {
      return {
        label: item.nickname,
        value: item.id,
        disabled: item.isDisabled,
      };
    });
    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  });
}
</script>
